/* SPDX-License-Identifier: GPL-2.0 */
/*
 * Scheduler internal types and methods:
 */
#ifndef KERNEL_SCHED_SCHED_H
#define KERNEL_SCHED_SCHED_H

#include <seminix/cpu.h>
#include <seminix/smp.h>
#include <seminix/slab.h>
#include <seminix/dump_stack.h>
#include <seminix/init.h>
#include <seminix/sysctl.h>
#include <seminix/jiffies.h>
#include <seminix/irqflags.h>
#include <seminix/interrupt.h>
#include <seminix/ratelimit.h>
#include <seminix/mutex.h>
#include <seminix/kthread.h>
#include <seminix/wait_bit.h>
#include <seminix/hashtable.h>
#include <seminix/completion.h>
#include <seminix/cpumask.h>
#include <seminix/syscall.h>
#include <seminix/preempt.h>
#include <seminix/init_task.h>
#include <seminix/stop_machine.h>
#include <seminix/sched/clock.h>
#include <seminix/sched/cpufreq.h>
#include <seminix/sched/deadline.h>
#include <seminix/sched/idle.h>
#include <seminix/sched/init.h>
#include <seminix/sched/jobctl.h>
#include <seminix/sched/load_avg.h>
#include <seminix/sched/mm.h>
#include <seminix/sched/prio.h>
#include <seminix/sched/rt.h>
#include <seminix/sched/signal.h>
#include <seminix/sched/task_stack.h>
#include <seminix/sched/task.h>
#include <seminix/sched/topology.h>
#include <seminix/sched/wake_q.h>
#include "cpupri.h"
#include "cpudeadline.h"
#include "../smpboot.h"

#define SCHED_DEBUG 1

#ifdef SCHED_DEBUG
# define SCHED_WARN_ON(x)	WARN_ONCE(x, #x)
#else
# define SCHED_WARN_ON(x)	({ (void)(x), 0; })
#endif

struct rq;

/* task_struct::on_rq states: */
#define TASK_ON_RQ_QUEUED	1
#define TASK_ON_RQ_MIGRATING	2

extern __read_mostly int scheduler_running;

/* 计算 cpu 负载更新时间 */
extern unsigned long calc_load_update;
/* 更新 cpu 负载 */
extern void calc_global_load_tick(struct rq *this_rq);

/* 更新 cpu load fair 内部 */
extern void cpu_load_update_active(struct rq *this_rq);

/*
 * Increase resolution of nice-level calculations for 64-bit architectures.
 * The extra resolution improves shares distribution and load balancing of
 * low-weight task groups (eg. nice +19 on an autogroup), deeper taskgroup
 * hierarchies, especially on larger systems. This is not a user-visible change
 * and does not change the user-interface for setting shares/weights.
 *
 * We increase resolution only if we have enough bits to allow this increased
 * resolution (i.e. 64-bit). The costs for increasing resolution when 32-bit
 * are pretty high and the returns do not justify the increased costs.
 *
 * Really only required when CONFIG_FAIR_GROUP_SCHED=y is also set, but to
 * increase coverage and consistency always enable it on 64-bit platforms.
 */
#ifdef CONFIG_64BIT
# define NICE_0_LOAD_SHIFT	(SCHED_FIXEDPOINT_SHIFT + SCHED_FIXEDPOINT_SHIFT)
# define scale_load(w)		((w) << SCHED_FIXEDPOINT_SHIFT)
# define scale_load_down(w)	((w) >> SCHED_FIXEDPOINT_SHIFT)
#else
# define NICE_0_LOAD_SHIFT	(SCHED_FIXEDPOINT_SHIFT)
# define scale_load(w)		(w)
# define scale_load_down(w)	(w)
#endif

/*
 * Task weight (visible to users) and its load (invisible to users) have
 * independent resolution, but they should be well calibrated. We use
 * scale_load() and scale_load_down(w) to convert between them. The
 * following must be true:
 *
 *  scale_load(sched_prio_to_weight[USER_PRIO(NICE_TO_PRIO(0))]) == NICE_0_LOAD
 *
 */
#define NICE_0_LOAD		(1L << NICE_0_LOAD_SHIFT)

/*
 * Single value that decides SCHED_DEADLINE internal math precision.
 * 10 -> just above 1us
 * 9  -> just above 0.5us
 */
#define DL_SCALE		10

/*
 * Single value that denotes runtime == period, ie unlimited time.
 */
#define RUNTIME_INF		((u64)~0ULL)

static inline int idle_policy(int policy)
{
    return policy == SCHED_IDLE;
}

static inline int fair_policy(int policy)
{
    return policy == SCHED_NORMAL || policy == SCHED_BATCH;
}

static inline int rt_policy(int policy)
{
    return policy == SCHED_FIFO || policy == SCHED_RR;
}

static inline int dl_policy(int policy)
{
    return policy == SCHED_DEADLINE;
}

static inline bool valid_policy(int policy)
{
    return idle_policy(policy) || fair_policy(policy) ||
        rt_policy(policy) || dl_policy(policy);
}

static inline int task_has_idle_policy(struct task_struct *p)
{
    return idle_policy(p->policy);
}

static inline int task_has_rt_policy(struct task_struct *p)
{
    return rt_policy(p->policy);
}

static inline int task_has_dl_policy(struct task_struct *p)
{
    return dl_policy(p->policy);
}

#define cap_scale(v, s) ((v)*(s) >> SCHED_CAPACITY_SHIFT)

/*
 * !! For sched_setattr_nocheck() (kernel) only !!
 *
 * This is actually gross. :(
 *
 * It is used to make schedutil kworker(s) higher priority than SCHED_DEADLINE
 * tasks, but still be able to sleep. We need this on platforms that cannot
 * atomically change clock frequency. Remove once fast switching will be
 * available on such platforms.
 *
 * SUGOV stands for SchedUtil GOVernor.
 */
#define SCHED_FLAG_SUGOV	0x10000000

static inline bool dl_entity_is_special(struct sched_dl_entity *dl_se)
{
#ifdef CONFIG_CPU_FREQ_GOV_SCHEDUTIL
    return unlikely(dl_se->flags & SCHED_FLAG_SUGOV);
#else
    return false;
#endif
}

/*
 * Tells if entity @a should preempt entity @b.
 */
static inline bool
dl_entity_preempt(struct sched_dl_entity *a, struct sched_dl_entity *b)
{
    return dl_entity_is_special(a) ||
           dl_time_before(a->deadline, b->deadline);
}

/*
 * This is the priority-queue data structure of the RT scheduling class:
 */
struct rt_prio_array {
    DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
    struct list_head queue[MAX_RT_PRIO];
};

struct rt_bandwidth {
    /* nests inside the rq lock: */
    raw_spinlock_t		rt_runtime_lock;
    ktime_t			rt_period;
    u64			rt_runtime;
    struct hrtimer		rt_period_timer;
    unsigned int		rt_period_active;
};

void __dl_clear_params(struct task_struct *p);

/*
 * To keep the bandwidth of -deadline tasks and groups under control
 * we need some place where:
 *  - store the maximum -deadline bandwidth of the system (the group);
 *  - cache the fraction of that bandwidth that is currently allocated.
 *
 * This is all done in the data structure below. It is similar to the
 * one used for RT-throttling (rt_bandwidth), with the main difference
 * that, since here we are only interested in admission control, we
 * do not decrease any runtime while the group "executes", neither we
 * need a timer to replenish it.
 *
 * With respect to SMP, the bandwidth is given on a per-CPU basis,
 * meaning that:
 *  - dl_bw (< 100%) is the bandwidth of the system (group) on each CPU;
 *  - dl_total_bw array contains, in the i-eth element, the currently
 *    allocated bandwidth on the i-eth CPU.
 * Moreover, groups consume bandwidth on each CPU, while tasks only
 * consume bandwidth on the CPU they're running on.
 * Finally, dl_total_bw_cpu is used to cache the index of dl_total_bw
 * that will be shown the next time the proc or cgroup controls will
 * be red. It on its turn can be changed by writing on its own
 * control.
 */
struct dl_bandwidth {
    raw_spinlock_t		dl_runtime_lock;
    u64			dl_runtime;
    u64			dl_period;
};

static inline int dl_bandwidth_enabled(void)
{
    return sysctl_sched_rt_runtime >= 0;
}

struct dl_bw {
    raw_spinlock_t		lock;
    u64			bw;
    u64			total_bw;
};

static inline void __dl_update(struct dl_bw *dl_b, i64 bw);

static inline
void __dl_sub(struct dl_bw *dl_b, u64 tsk_bw, int cpus)
{
    dl_b->total_bw -= tsk_bw;
    __dl_update(dl_b, (i32)tsk_bw / cpus);
}

static inline
void __dl_add(struct dl_bw *dl_b, u64 tsk_bw, int cpus)
{
    dl_b->total_bw += tsk_bw;
    __dl_update(dl_b, -((i32)tsk_bw / cpus));
}

static inline
bool __dl_overflow(struct dl_bw *dl_b, int cpus, u64 old_bw, u64 new_bw)
{
    return dl_b->bw != -1 &&
           dl_b->bw * cpus < dl_b->total_bw - old_bw + new_bw;
}

extern void init_dl_bw(struct dl_bw *dl_b);
extern int  sched_dl_global_validate(void);
extern void sched_dl_do_global(void);
extern int  sched_dl_overflow(struct task_struct *p, int policy, const struct sched_attr *attr);
extern void __setparam_dl(struct task_struct *p, const struct sched_attr *attr);
extern void __getparam_dl(struct task_struct *p, struct sched_attr *attr);
extern bool __checkparam_dl(const struct sched_attr *attr);
extern bool dl_param_changed(struct task_struct *p, const struct sched_attr *attr);

/* CFS-related fields in a runqueue */
struct cfs_rq {
    struct load_weight	load;
    unsigned long		runnable_weight;
    unsigned int		nr_running;
    unsigned int		h_nr_running;

    u64			exec_clock;
    u64			min_vruntime;
#ifndef CONFIG_64BIT
    u64			min_vruntime_copy;
#endif

    struct rb_root_cached	tasks_timeline;

    /*
     * 'curr' points to currently running entity on this cfs_rq.
     * It is set to NULL otherwise (i.e when none are currently running).
     */
    struct sched_entity	*curr;
    struct sched_entity	*next;
    struct sched_entity	*last;
    struct sched_entity	*skip;

    /*
     * CFS load tracking
     */
    struct sched_avg	avg;
#ifndef CONFIG_64BIT
    u64			load_last_update_time_copy;
#endif
    struct {
        raw_spinlock_t	lock ____cacheline_aligned;
        int		nr;
        unsigned long	load_avg;
        unsigned long	util_avg;
        unsigned long	runnable_sum;
    } removed;
};

static inline int rt_bandwidth_enabled(void)
{
    return sysctl_sched_rt_runtime >= 0;
}

/* Real-Time classes' related field in a runqueue: */
struct rt_rq {
    struct rt_prio_array	active;
    unsigned int		rt_nr_running;
    unsigned int		rr_nr_running;
    struct {
        int		curr; /* highest queued rt task prio */
        int		next; /* next highest */
    } highest_prio;
    unsigned long		rt_nr_migratory;
    unsigned long		rt_nr_total;
    int			overloaded;
    struct plist_head	pushable_tasks;
    int			rt_queued;

    int			rt_throttled;
    u64			rt_time;
    u64			rt_runtime;
    /* Nests inside the rq lock: */
    raw_spinlock_t		rt_runtime_lock;
};

static inline bool rt_rq_is_runnable(struct rt_rq *rt_rq)
{
    return rt_rq->rt_queued && rt_rq->rt_nr_running;
}

/* Deadline class' related fields in a runqueue */
struct dl_rq {
    /* runqueue is an rbtree, ordered by deadline */
    struct rb_root_cached	root;

    unsigned long		dl_nr_running;

    /*
     * Deadline values of the currently executing and the
     * earliest ready task on this rq. Caching these facilitates
     * the decision whether or not a ready but not running task
     * should migrate somewhere else.
     */
    struct {
        u64		curr;
        u64		next;
    } earliest_dl;

    unsigned long		dl_nr_migratory;
    int			overloaded;

    /*
     * Tasks on this rq that can be pushed away. They are kept in
     * an rb-tree, ordered by tasks' deadlines, with caching
     * of the leftmost (earliest deadline) element.
     */
    struct rb_root_cached	pushable_dl_tasks_root;
    /*
     * "Active utilization" for this runqueue: increased when a
     * task wakes up (becomes TASK_RUNNING) and decreased when a
     * task blocks
     */
    u64			running_bw;

    /*
     * Utilization of the tasks "assigned" to this runqueue (including
     * the tasks that are in runqueue and the tasks that executed on this
     * CPU and blocked). Increased when a task moves to this runqueue, and
     * decreased when the task moves away (migrates, changes scheduling
     * policy, or terminates).
     * This is needed to compute the "inactive utilization" for the
     * runqueue (inactive utilization = this_bw - running_bw).
     */
    u64			this_bw;
    u64			extra_bw;

    /*
     * Inverse of the fraction of CPU utilization that can be reclaimed
     * by the GRUB algorithm.
     */
    u64			bw_ratio;
};

/*
 * XXX we want to get rid of these helpers and use the full load resolution.
 */
static inline long se_weight(struct sched_entity *se)
{
    return scale_load_down(se->load.weight);
}

static inline long se_runnable(struct sched_entity *se)
{
    return scale_load_down(se->runnable_weight);
}

/* Scheduling group status flags */
#define SG_OVERLOAD		0x1 /* More than one runnable task on a CPU. */
#define SG_OVERUTILIZED		0x2 /* One or more CPUs are over-utilized. */

struct root_domain {
    struct cpumask		span;

    atomic_t		rto_count;
    struct cpumask  rto_mask;
    struct cpupri		cpupri;

    /*
     * The bit corresponding to a CPU gets set here if such CPU has more
     * than one runnable -deadline task (as it is below for RT tasks).
     */
    struct cpumask		dlo_mask;
    atomic_t		dlo_count;
    struct dl_bw		dl_bw;
    struct cpudl		cpudl;

    spinlock_t loadavg_lock;
    unsigned long    max_loadavg, min_loadavg;
    int    max_loadavg_cpu, min_loadavg_cpu;

	/*
	 * Indicate pullable load on at least one CPU, e.g:
	 * - More than one runnable task
	 * - Running task is misfit
	 */
	int			overload;

	/* Indicate one or more cpus over-utilized (tipping point) */
	int			overutilized;
};

/*
 * This is the main, per-CPU runqueue data structure.
 *
 * Locking rule: those places that want to lock multiple runqueues
 * (such as the load balancing or the thread migration code), lock
 * acquire operations must be ordered by ascending &runqueue.
 */
struct rq {
    /* runqueue lock: */
    raw_spinlock_t		lock;

    /*
     * nr_running and cpu_load should be in the same cacheline because
     * remote CPUs use both these fields when doing load calculation.
     */
    unsigned int		nr_running;

    #define CPU_LOAD_IDX_MAX 5
    unsigned long		cpu_load[CPU_LOAD_IDX_MAX];

    unsigned long		last_load_update_tick;
    unsigned long		last_blocked_load_update_tick;

    /* capture load from *all* tasks on this CPU: */
    struct load_weight	load;
    unsigned long		nr_load_updates;
    u64			nr_switches;

    struct cfs_rq		cfs;
    struct rt_rq		rt;
    struct dl_rq		dl;

    /*
     * This is part of a global counter where only the total sum
     * over all CPUs matters. A task can increase this counter on
     * one CPU and if it got migrated afterwards it may decrease
     * it on another CPU. Always updated under the runqueue lock:
     */
    unsigned long		nr_uninterruptible;

    struct task_struct	*curr;
    struct task_struct	*idle;
    struct task_struct	*stop;

    struct mm_struct	*prev_mm;

    unsigned int		clock_update_flags;
    u64			clock;
    u64			clock_task; /* clock 和 clock_task 相等, 当存在半虚拟化等支持时 clock_task <= clock */

    atomic_t		nr_iowait;

    struct root_domain *rd;

    unsigned long		cpu_capacity;
    unsigned long		cpu_capacity_orig;

    struct callback_head	*balance_callback;

    struct cpu_stop_work	active_balance_work;

    /* CPU of this runqueue: */
    int			cpu;
    int			online;

    struct list_head cfs_tasks;

    struct sched_avg	avg_rt;
    struct sched_avg	avg_dl;

    u64			idle_stamp;
    u64			avg_idle;

    /* This is used to determine avg_idle's max value */
    u64			max_idle_balance_cost;

    /* calc_load related fields */
    unsigned long		calc_load_update;
    long			calc_load_active;

    int			hrtick_csd_pending;
    call_single_data_t	hrtick_csd;
    struct hrtimer		hrtick_timer;

    struct llist_head	wake_list;
};

static inline int cpu_of(struct rq *rq)
{
    return rq->cpu;
}

DECLARE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);

#define cpu_rq(cpu)		(&per_cpu(runqueues, (cpu)))
#define this_rq()		this_cpu_ptr(&runqueues)
#define task_rq(p)		cpu_rq(task_cpu(p))
#define cpu_curr(cpu)		(cpu_rq(cpu)->curr)
#define raw_rq()		raw_cpu_ptr(&runqueues)

extern void update_rq_clock(struct rq *rq);

static inline u64 __rq_clock_broken(struct rq *rq)
{
    return READ_ONCE(rq->clock);
}

/*
 * rq::clock_update_flags bits
 *
 * %RQCF_REQ_SKIP - will request skipping of clock update on the next
 *  call to __schedule(). This is an optimisation to avoid
 *  neighbouring rq clock updates.
 *
 * %RQCF_ACT_SKIP - is set from inside of __schedule() when skipping is
 *  in effect and calls to update_rq_clock() are being ignored.
 *
 * %RQCF_UPDATED - is a debug flag that indicates whether a call has been
 *  made to update_rq_clock() since the last time rq::lock was pinned.
 *
 * If inside of __schedule(), clock_update_flags will have been
 * shifted left (a left shift is a cheap operation for the fast path
 * to promote %RQCF_REQ_SKIP to %RQCF_ACT_SKIP), so you must use,
 *
 *	if (rq-clock_update_flags >= RQCF_UPDATED)
 *
 * to check if %RQCF_UPADTED is set. It'll never be shifted more than
 * one position though, because the next rq_unpin_lock() will shift it
 * back.
 */
#define RQCF_REQ_SKIP		0x01
#define RQCF_ACT_SKIP		0x02
#define RQCF_UPDATED		0x04

static inline void assert_clock_updated(struct rq *rq)
{
    /*
     * The only reason for not seeing a clock update since the
     * last rq_pin_lock() is if we're currently skipping updates.
     */
    SCHED_WARN_ON(rq->clock_update_flags < RQCF_ACT_SKIP);
}

static inline u64 rq_clock(struct rq *rq)
{
    assert_clock_updated(rq);

    return rq->clock;
}

static inline u64 rq_clock_task(struct rq *rq)
{
    assert_clock_updated(rq);

    return rq->clock_task;
}

static inline void rq_clock_skip_update(struct rq *rq)
{
    rq->clock_update_flags |= RQCF_REQ_SKIP;
}

/*
 * See rt task throttling, which is the only time a skip
 * request is cancelled.
 */
static inline void rq_clock_cancel_skipupdate(struct rq *rq)
{
    rq->clock_update_flags &= ~RQCF_REQ_SKIP;
}

struct rq_flags {
    unsigned long flags;
#ifdef SCHED_DEBUG
    /*
     * A copy of (rq::clock_update_flags & RQCF_UPDATED) for the
     * current pin context is stashed here in case it needs to be
     * restored in rq_repin_lock().
     */
    unsigned int clock_update_flags;
#endif
};

static inline void rq_pin_lock(struct rq *rq, struct rq_flags *rf)
{
#ifdef SCHED_DEBUG
    rq->clock_update_flags &= (RQCF_REQ_SKIP|RQCF_ACT_SKIP);
    rf->clock_update_flags = 0;
#endif
}

static inline void rq_unpin_lock(struct rq *rq, struct rq_flags *rf)
{
#ifdef SCHED_DEBUG
    if (rq->clock_update_flags > RQCF_ACT_SKIP)
        rf->clock_update_flags = RQCF_UPDATED;
#endif
}

static inline void rq_repin_lock(struct rq *rq, struct rq_flags *rf)
{
#ifdef SCHED_DEBUG
    /*
     * Restore the value we stashed in @rf for this pin context.
     */
    rq->clock_update_flags |= rf->clock_update_flags;
#endif
}

struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
    __acquires(rq->lock);

struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
    __acquires(p->pi_lock)
    __acquires(rq->lock);

static inline void __task_rq_unlock(struct rq *rq, struct rq_flags *rf)
    __releases(rq->lock)
{
    rq_unpin_lock(rq, rf);
    raw_spin_unlock(&rq->lock);
}

static inline void
task_rq_unlock(struct rq *rq, struct task_struct *p, struct rq_flags *rf)
    __releases(rq->lock)
    __releases(p->pi_lock)
{
    rq_unpin_lock(rq, rf);
    raw_spin_unlock(&rq->lock);
    raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
}

static inline void
rq_lock_irqsave(struct rq *rq, struct rq_flags *rf)
    __acquires(rq->lock)
{
    raw_spin_lock_irqsave(&rq->lock, rf->flags);
    rq_pin_lock(rq, rf);
}

static inline void
rq_lock_irq(struct rq *rq, struct rq_flags *rf)
    __acquires(rq->lock)
{
    raw_spin_lock_irq(&rq->lock);
    rq_pin_lock(rq, rf);
}

static inline void
rq_lock(struct rq *rq, struct rq_flags *rf)
    __acquires(rq->lock)
{
    raw_spin_lock(&rq->lock);
    rq_pin_lock(rq, rf);
}

static inline void
rq_relock(struct rq *rq, struct rq_flags *rf)
    __acquires(rq->lock)
{
    raw_spin_lock(&rq->lock);
    rq_repin_lock(rq, rf);
}

static inline void
rq_unlock_irqrestore(struct rq *rq, struct rq_flags *rf)
    __releases(rq->lock)
{
    rq_unpin_lock(rq, rf);
    raw_spin_unlock_irqrestore(&rq->lock, rf->flags);
}

static inline void
rq_unlock_irq(struct rq *rq, struct rq_flags *rf)
    __releases(rq->lock)
{
    rq_unpin_lock(rq, rf);
    raw_spin_unlock_irq(&rq->lock);
}

static inline void
rq_unlock(struct rq *rq, struct rq_flags *rf)
    __releases(rq->lock)
{
    rq_unpin_lock(rq, rf);
    raw_spin_unlock(&rq->lock);
}

static inline struct rq *
this_rq_lock_irq(struct rq_flags *rf)
    __acquires(rq->lock)
{
    struct rq *rq;

    local_irq_disable();
    rq = this_rq();
    rq_lock(rq, rf);
    return rq;
}

static inline void
queue_balance_callback(struct rq *rq,
               struct callback_head *head,
               void (*func)(struct rq *rq))
{
    if (unlikely(head->next))
        return;

    head->func = (void (*)(struct callback_head *))func;
    head->next = rq->balance_callback;
    rq->balance_callback = head;
}

extern void sched_ttwu_pending(void);

static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
{
    /*
     * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
     * successfully executed on another CPU. We must ensure that updates of
     * per-task data have been completed by this moment.
     */
    smp_wmb();
    p->cpu = cpu;
    p->wake_cpu = cpu;
}

#ifdef SCHED_DEBUG
#define const_debug __read_mostly
#else
#define const_debug const
#endif

#define SCHED_FEAT(name, enabled)	\
    __SCHED_FEAT_##name ,

enum {
#include "features.h"
    __SCHED_FEAT_NR,
};

#undef SCHED_FEAT

/*
 * Each translation unit has its own copy of sysctl_sched_features to allow
 * constants propagation at compile time and compiler optimization based on
 * features default.
 */
#define SCHED_FEAT(name, enabled)	\
    (1UL << __SCHED_FEAT_##name) * enabled |
static const_debug __maybe_unused unsigned int sysctl_sched_features =
#include "features.h"
    0;
#undef SCHED_FEAT

#define sched_feat(x) !!(sysctl_sched_features & (1UL << __SCHED_FEAT_##x))

static inline u64 global_rt_period(void)
{
    return (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
}

static inline u64 global_rt_runtime(void)
{
    if (sysctl_sched_rt_runtime < 0)
        return RUNTIME_INF;

    return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC;
}

static inline int task_current(struct rq *rq, struct task_struct *p)
{
    return rq->curr == p;
}

static inline int task_running(struct rq *rq, struct task_struct *p)
{
    return p->on_cpu;
}

static inline int task_on_rq_queued(struct task_struct *p)
{
    return p->on_rq == TASK_ON_RQ_QUEUED;
}

static inline int task_on_rq_migrating(struct task_struct *p)
{
    return p->on_rq == TASK_ON_RQ_MIGRATING;
}

/*
 * wake flags
 */
#define WF_SYNC			0x01		/* Waker goes to sleep after wakeup */
#define WF_FORK			0x02		/* Child wakeup after fork */
#define WF_MIGRATED		0x4		/* Internal use, task got migrated */

/*
 * To aid in avoiding the subversion of "niceness" due to uneven distribution
 * of tasks with abnormal "nice" values across CPUs the contribution that
 * each task makes to its run queue's load is weighted according to its
 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
 * scaled version of the new time slice allocation that they receive on time
 * slice expiry etc.
 */

#define WEIGHT_IDLEPRIO		3
#define WMULT_IDLEPRIO		1431655765

extern const int		sched_prio_to_weight[40];
extern const u32		sched_prio_to_wmult[40];

/*
 * {de,en}queue flags:
 *
 * DEQUEUE_SLEEP  - task is no longer runnable
 * ENQUEUE_WAKEUP - task just became runnable
 *
 * SAVE/RESTORE - an otherwise spurious dequeue/enqueue, done to ensure tasks
 *                are in a known state which allows modification. Such pairs
 *                should preserve as much state as possible.
 *
 * MOVE - paired with SAVE/RESTORE, explicitly does not preserve the location
 *        in the runqueue.
 *
 * ENQUEUE_HEAD      - place at front of runqueue (tail if not specified)
 * ENQUEUE_REPLENISH - CBS (replenish runtime and postpone deadline)
 * ENQUEUE_MIGRATED  - the task was migrated during wakeup
 *
 */

#define DEQUEUE_SLEEP		0x01
#define DEQUEUE_SAVE		0x02 /* Matches ENQUEUE_RESTORE */
#define DEQUEUE_MOVE		0x04 /* Matches ENQUEUE_MOVE */
#define DEQUEUE_NOCLOCK		0x08 /* Matches ENQUEUE_NOCLOCK */

#define ENQUEUE_WAKEUP		0x01
#define ENQUEUE_RESTORE		0x02
#define ENQUEUE_MOVE		0x04
#define ENQUEUE_NOCLOCK		0x08

#define ENQUEUE_HEAD		0x10
#define ENQUEUE_REPLENISH	0x20
#define ENQUEUE_MIGRATED	0x40

#define RETRY_TASK		((void *)-1UL)

struct sched_class {
    const struct sched_class *next;

    void (*enqueue_task) (struct rq *rq, struct task_struct *p, int flags);
    void (*dequeue_task) (struct rq *rq, struct task_struct *p, int flags);
    void (*yield_task)   (struct rq *rq);
    bool (*yield_to_task)(struct rq *rq, struct task_struct *p, bool preempt);

    void (*check_preempt_curr)(struct rq *rq, struct task_struct *p, int flags);

    /*
     * It is the responsibility of the pick_next_task() method that will
     * return the next task to call put_prev_task() on the @prev task or
     * something equivalent.
     *
     * May return RETRY_TASK when it finds a higher prio class has runnable
     * tasks.
     */
    struct task_struct * (*pick_next_task)(struct rq *rq,
                           struct task_struct *prev,
                           struct rq_flags *rf);
    void (*put_prev_task)(struct rq *rq, struct task_struct *p);

    int  (*select_task_rq)(struct task_struct *p, int task_cpu, int sd_flag, int flags);
    void (*migrate_task_rq)(struct task_struct *p, int new_cpu);

    void (*task_woken)(struct rq *this_rq, struct task_struct *task);

    void (*set_cpus_allowed)(struct task_struct *p,
                 const struct cpumask *newmask);

    void (*rq_online)(struct rq *rq);
    void (*rq_offline)(struct rq *rq);

    void (*set_curr_task)(struct rq *rq);
    void (*task_tick)(struct rq *rq, struct task_struct *p, int queued);
    void (*task_fork)(struct task_struct *p);
    void (*task_dead)(struct task_struct *p);

    /*
     * The switched_from() call is allowed to drop rq->lock, therefore we
     * cannot assume the switched_from/switched_to pair is serliazed by
     * rq->lock. They are however serialized by p->pi_lock.
     */
    void (*switched_from)(struct rq *this_rq, struct task_struct *task);
    void (*switched_to)  (struct rq *this_rq, struct task_struct *task);
    void (*prio_changed) (struct rq *this_rq, struct task_struct *task,
                  int oldprio);

    unsigned int (*get_rr_interval)(struct rq *rq,
                    struct task_struct *task);

    void (*update_curr)(struct rq *rq);
};

static inline void put_prev_task(struct rq *rq, struct task_struct *prev)
{
    prev->sched_class->put_prev_task(rq, prev);
}

static inline void set_curr_task(struct rq *rq, struct task_struct *curr)
{
    curr->sched_class->set_curr_task(rq);
}

#define sched_class_highest (&stop_sched_class)
#define for_each_class(class) \
   for (class = sched_class_highest; class; class = class->next)

extern const struct sched_class stop_sched_class;
extern const struct sched_class dl_sched_class;
extern const struct sched_class rt_sched_class;
extern const struct sched_class fair_sched_class;
extern const struct sched_class idle_sched_class;

extern void trigger_load_balance(struct rq *rq);

extern void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask);

extern void schedule_idle(void);

extern void sysrq_sched_debug_show(void);
extern void sched_init_granularity(void);

extern void init_sched_dl_class(void);
extern void init_sched_rt_class(void);
extern void init_sched_fair_class(void);

extern void reweight_task(struct task_struct *p, int prio);

extern void resched_curr(struct rq *rq);
extern void resched_cpu(int cpu);

extern struct rt_bandwidth def_rt_bandwidth;
extern void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime);

extern struct dl_bandwidth def_dl_bandwidth;
extern void init_dl_bandwidth(struct dl_bandwidth *dl_b, u64 period, u64 runtime);
extern void init_dl_task_timer(struct sched_dl_entity *dl_se);
extern void init_dl_inactive_task_timer(struct sched_dl_entity *dl_se);
extern void init_dl_rq_bw_ratio(struct dl_rq *dl_rq);

#define BW_SHIFT		20
#define BW_UNIT			(1 << BW_SHIFT)
#define RATIO_SHIFT		8
unsigned long to_ratio(u64 period, u64 runtime);

extern void init_entity_runnable_average(struct sched_entity *se);
extern void post_init_entity_util_avg(struct sched_entity *se);

static inline void add_nr_running(struct rq *rq, unsigned count)
{
    unsigned prev_nr = rq->nr_running;

    rq->nr_running = prev_nr + count;

    if (prev_nr < 2 && rq->nr_running >= 2) {
        if (!READ_ONCE(rq->rd->overload))
            WRITE_ONCE(rq->rd->overload, 1);
    }
}

static inline void sub_nr_running(struct rq *rq, unsigned count)
{
    rq->nr_running -= count;
}

extern void activate_task(struct rq *rq, struct task_struct *p, int flags);
extern void deactivate_task(struct rq *rq, struct task_struct *p, int flags);

extern void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags);

extern const_debug unsigned int sysctl_sched_nr_migrate;
extern const_debug unsigned int sysctl_sched_migration_cost;

/*
 * Use hrtick when:
 *  - enabled by features
 *  - hrtimer is actually high res
 */
static inline int hrtick_enabled(struct rq *rq)
{
    if (!sched_feat(HRTICK))
        return 0;
    if (!cpu_online(cpu_of(rq)))
        return 0;
    return 1;
}

void hrtick_start(struct rq *rq, u64 delay);

static inline void double_rq_lock(struct rq *rq1, struct rq *rq2);

/*
 * fair double_lock_balance: Safely acquires both rq->locks in a fair
 * way at the expense of forcing extra atomic operations in all
 * invocations.  This assures that the double_lock is acquired using the
 * same underlying policy as the spinlock_t on this architecture, which
 * reduces latency compared to the unfair variant below.  However, it
 * also adds more overhead and therefore may reduce throughput.
 */
static inline int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
    __releases(this_rq->lock)
    __acquires(busiest->lock)
    __acquires(this_rq->lock)
{
    raw_spin_unlock(&this_rq->lock);
    double_rq_lock(this_rq, busiest);

    return 1;
}

/*
 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
 */
static inline int double_lock_balance(struct rq *this_rq, struct rq *busiest)
{
    if (unlikely(!irqs_disabled())) {
        /* printk() doesn't work well under rq->lock */
        raw_spin_unlock(&this_rq->lock);
        BUG_ON(1);
    }

    return _double_lock_balance(this_rq, busiest);
}

static inline void double_unlock_balance(struct rq *this_rq, struct rq *busiest)
    __releases(busiest->lock)
{
    raw_spin_unlock(&busiest->lock);
}

static inline void double_lock(spinlock_t *l1, spinlock_t *l2)
{
    if (l1 > l2)
        swap(l1, l2);

    spin_lock(l1);
    spin_lock_nested(l2, 1);
}

static inline void double_lock_irq(spinlock_t *l1, spinlock_t *l2)
{
    if (l1 > l2)
        swap(l1, l2);

    spin_lock_irq(l1);
    spin_lock_nested(l2, 1);
}

static inline void double_raw_lock(raw_spinlock_t *l1, raw_spinlock_t *l2)
{
    if (l1 > l2)
        swap(l1, l2);

    raw_spin_lock(l1);
    raw_spin_lock_nested(l2, 1);
}

/*
 * double_rq_lock - safely lock two runqueues
 *
 * Note this does not disable interrupts like task_rq_lock,
 * you need to do so manually before calling.
 */
static inline void double_rq_lock(struct rq *rq1, struct rq *rq2)
    __acquires(rq1->lock)
    __acquires(rq2->lock)
{
    BUG_ON(!irqs_disabled());
    if (rq1 == rq2) {
        raw_spin_lock(&rq1->lock);
        __acquire(rq2->lock);	/* Fake it out ;) */
    } else {
        if (rq1 < rq2) {
            raw_spin_lock(&rq1->lock);
            raw_spin_lock_nested(&rq2->lock, 1);
        } else {
            raw_spin_lock(&rq2->lock);
            raw_spin_lock_nested(&rq1->lock, 1);
        }
    }
}

/*
 * double_rq_unlock - safely unlock two runqueues
 *
 * Note this does not restore interrupts like task_rq_unlock,
 * you need to do so manually after calling.
 */
static inline void double_rq_unlock(struct rq *rq1, struct rq *rq2)
    __releases(rq1->lock)
    __releases(rq2->lock)
{
    raw_spin_unlock(&rq1->lock);
    if (rq1 != rq2)
        raw_spin_unlock(&rq2->lock);
    else
        __release(rq2->lock);
}

extern void set_rq_online(struct rq *rq);
extern void set_rq_offline(struct rq *rq);
extern bool sched_smp_initialized;

extern struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq);
extern struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq);

extern void init_cfs_rq(struct cfs_rq *cfs_rq);
extern void init_rt_rq(struct rt_rq *rt_rq);
extern void init_dl_rq(struct dl_rq *dl_rq);

static inline
void __dl_update(struct dl_bw *dl_b, i64 bw)
{
    struct root_domain *rd = container_of(dl_b, struct root_domain, dl_bw);
    int i;

    RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
             "sched RCU must be held");
    for_each_cpu_and(i, &rd->span, cpu_online_mask) {
        struct rq *rq = cpu_rq(i);
        rq->dl.extra_bw += bw;
    }
}

extern int sched_rr_timeslice;

#endif /* !KERNEL_SCHED_SCHED_H */
